<?php

namespace app\admin\controller\car;

use app\common\controller\Backend;
use app\common\model\Car;
use app\common\model\CarImages;
use app\common\model\Images;
use think\Db;
use think\Exception;


/**
 * 车品牌管理
 *
 * @icon fa fa-circle-o
 */
class Image extends Backend
{

    protected $searchFields = 'car_numbers,vin';

    /**
     * Brands模型对象
     * @var \app\common\model\CarImages
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new CarImages();

    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['car'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 通过
     * @param null $ids
     * @throws \think\exception\DbException
     */
    public function pass($ids=null)
    {
        Db::startTrans();
        try{
            if (empty($ids)){
                throw new Exception('参数ID缺失');
            }
            $info = CarImages::get(['id'=>$ids,'status'=>0]);
            if (empty($info)){
                throw new Exception('该条记录信息不存在');
            }
            $old_img = '';
            if (!empty($info->url))
                $old_img = removeDomain($info->url);
            $info->url = removeDomain($info->new_url);
            $info->new_url = '';
            $info->status = 1;
            $info->save();
            Db::commit();
            if (!empty($old_img))
                unlink(substr($old_img,1));
            $this->success();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 拒绝
     * @param null $ids
     * @throws \think\exception\DbException
     */
    public function refuse($ids=null)
    {
        Db::startTrans();
        try{
            if (empty($ids)){
                throw new Exception('参数ID缺失');
            }
            $info = CarImages::get(['id'=>$ids,'status'=>0]);
            if (empty($info)){
                throw new Exception('该条记录信息不存在');
            }
            $info->status = 2;
            $info->save();
            Db::commit();
            $this->success();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }


}
